package com.jt.www.job.issue;

import com.alibaba.fastjson.JSONObject;
import com.jt.www.admin.user.service.UserService;
import com.jt.www.common.service.JobQueryListService;
import com.jt.www.common.service.MessageService;
import com.jt.www.common.service.SendEmailsService;
import com.jt.www.dao.mapper.issue.mapper.IssuePolicyLogEntityMapper;
import com.jt.www.enums.issue.IssueEnum;
import com.jt.www.enums.issue.PolicyEnum;
import com.jt.www.model.entity.MessageInfoEntity;
import com.jt.www.model.entity.User;
import com.jt.www.model.issue.entity.IssuePolicyLogEntity;
import com.jt.www.model.mail.dto.MailDTO;
import com.jt.www.model.param.endorse.AppDetailProParam;
import com.jt.www.model.pay.ResBindDetailQo;
import com.jt.www.model.pay.ResBindQo;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.vo.endorse.AppDetailProVo;
import com.jt.www.model.vo.sdCheck.HolderForProVO;
import com.jt.www.model.vo.sdCheck.PolAttachmentProVO;
import com.jt.www.remote.DexClient;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtils;
import com.jt.www.util.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * 绑定资源
 *
 * @author admin_ltf
 * @create 2019-06-30 09:43
 */

@Component
@EnableScheduling
public class CheckBindResourceTask implements SchedulingConfigurer {

    public static final Logger log = LoggerFactory.getLogger(CheckBindResourceTask.class);
    private final static Integer MESSAGE_TYPE = 2;// 投保单
    /**
     * 单个服务器出单查询缓存失效时间 因不同的定时任务决定
     */
    private static final long ISSUE_TIME_OUT = 60L;
    /**
     * 电子保单是否绑定的定时任务 缓存key
     */
    private static final String ISSUE_LOCK_KEY = "EDU_ISSUE";
    @Autowired
    IssuePolicyLogEntityMapper issuePolicyLogEntityMapper;
    @Autowired
    JobQueryListService jobQueryListService;
    @Autowired
    InsClient insClient;
    @Autowired
    DexClient dexClient;
    @Autowired
    SendEmailsService emailsService;
    @Autowired
    UserService userService;
    private MessageService messageService;
    /**
     * 任务开关
     */

    @Value("${jtpf.issue.open}")
    private int checkOpen;
    /**
     * 任务执行周期
     */

    @Value("${jtpf.issue.cron}")
    private String cron;// 每隔一分钟执行一次

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if (checkOpen != 1) {
            return;
        }
        Runnable task0 = () -> checkStart();
        Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
        taskRegistrar.addTriggerTask(task0, trigger0);
    }

    private void checkStart() {
        if (!RedisUtil.setLock(ISSUE_LOCK_KEY, "1", ISSUE_TIME_OUT)) {
            return;
        }
        String currentTime = DateUtils.getCurrentTime();
        log.info(currentTime + "CheckBindResourceTask start,检查出单电子保单绑定资源的的任务开始...");
        //
        Weekend<IssuePolicyLogEntity> weekend = Weekend.of(IssuePolicyLogEntity.class);
        WeekendCriteria<IssuePolicyLogEntity, Object> criteria = weekend.weekendCriteria();
        List<String> statusList = new ArrayList<>();
        statusList.add("1");
        statusList.add("3");
        criteria.andIn(IssuePolicyLogEntity::getStatus, statusList);
        criteria.andLessThan(IssuePolicyLogEntity::getTimes, 6);
        criteria.andEqualTo(IssuePolicyLogEntity::getType, "1");
        List<IssuePolicyLogEntity> resultList = jobQueryListService.getJobProcessIssuePolicyLogList(weekend);
        if (resultList != null && resultList.size() > 0) {
            for (IssuePolicyLogEntity t : resultList) {
                String ifCode = t.getIfCode();
                switch (ifCode) {
                    case "20190528001":
                    case "20190528002":
                    case "20190528003":
                        //华泰产品（泰然无忧百万医疗） or  //华泰产品（华泰财险成长护航重疾险） or //华泰产品（华泰财险安康保护伞）
                        handleHT(t);
                        break;
                    case "20190516002":
                        //山东产品（山东省校（园）方责任保险项目）
                        handleSD(t);
                        break;
                    case "20200312002":
                        //云南学平险
                        handleYNXPX(t);
                        break;
                    case "20190516006":
                    case "202008271514410":
                    case "202010231517560":
                        //云南非九（校方综合防范保障保险、教职员工校方责任保险、云南省校方责任保险、校园食品安全责任保险）
                        handleYNFJ(t);
                        break;
                    case "20190515002":
                    case "20190726012":
                    case "20190805002":
                        //1实责（全国职业院校学生实习责任保险）  2校责（校方责任保险）
                        handleXZANDSZ(t);
                        break;
                    case "20190515026":
                        //学责（学生安全责任保险）
                        handleXZ(t);
                        break;
                    case "20190515006":
                    case "20200211001":
                    case "20200330006":
                    case "202006171149460":
                    case "202008191339340":
                        //阳光财产安责保护伞
                        handleAZBHS(t);
                        break;
                    case "20190802002":
                        //食品险（校园食品安全责任保险）
                        handleSPX(t);
                        break;
                    case "20190729001":
                    case "202008181443590":
                    case "202008201400250"://临沂学平险与徐州方式相同
                        //徐州学平险（徐州学平意外险/徐州监护人责任险）
                        handleXZXPX(t);
                        break;
                    case "20190805001": //济宁学平险
                    case "20190807001": //校园食品
                        handleEpolicy(t, IssueEnum.getIssueEnum(ifCode));
                        break;
                    case "20190518001":
                        //实责校责（大地）
                        handleSZXZDD(t);
                        break;
                    case "20190726017"://实责校责（太平）
                    case "20190731001":   //实责校责（中华联合）
                    case "20190827001": //新国寿财
                        handleSZXZ(t);
                        break;
                    case "20190802001":
                    case "20190909101": //食品险国寿财
                        //食品险（太平）
                        handleSPXTP(t);
                        break;
                   /* case "20190726012":
                        //实责校责（阳光）
                        handleXSZAndXZ(t);
                        break;*/
                    /*case "20190805002":*/
                    //食品险（阳光）
                    //handleSPXSP(t);
                    /*    break;*/
                    case "202007231708310":
                        handleJNXP(t);
                        break;
                    case "202008041342390":
                    case "202008180929030":
                    case "202008190924410":
                    case "202008190922090":
                        handleGD(t);
                        break;
                    case "202008241457160":
                        handleJiNingXPX(t);
                        break;
                    case "202009090116140":
                        handleJiNingXPXOnline(t);
                        break;
                    case "202009171037520":
                        handleQiDong(t);
                        break;
                    default:
                        log.error("{}错误的ifCode:{}", currentTime, ifCode);
                }
            }
        }
        log.info(currentTime + "CheckMessageConsumeFailTask end,检查出单电子保单绑定资源的的任务结束...");
    }

    /**
     * 华泰产品（泰然无忧百万医疗）
     *
     * @param t
     */
    private void handleHT(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;
        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "我学保华泰下载电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20190516022", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "我学保华泰下载电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String fileId = responseEntity.getBody();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

    /**
     * 济南学平险电子保单下载
     *
     * @param t
     */
    private void handleJNXP(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;
        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "济南学平险电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "202007251346580", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "济南学平险下载电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                String elecbody = responseEntity.getBody();
                Document elecdoc = DocumentHelper.parseText(elecbody);
                Element elecbodyElement = elecdoc.getRootElement();
                Element elecdata = elecbodyElement.element("data");
                String fileId = "";
                String consumeStatus = "";
                if (elecdata == null || "".equals(elecdata)) {
                    consumeStatus = "3";
                    t.setTimes(times);
                    log.error("{} 调用济南电子保单接口任务 返回结果{}", JsonUtils.toJson(elecbodyElement));
                } else {
                    consumeStatus = "2";
                    fileId = elecdata.getStringValue();
                    t.setEPolicyId(fileId);
                    // 下载电子保单成功，更新数据库，绑定资源
                    log.info("{} 调用济南电子保单接口任务 fileId ：{}", fileId);
                }
                t.setStatus(consumeStatus);
                bindresource(t);
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

    /**
     * 1实责（全国职业院校学生实习责任保险）  2校责（校方责任保险）
     *
     * @param t
     */
    private void handleXZANDSZ(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                String policy = PolicyEnum.getPolicyOrInvoiceByIfCode(t.getIfCode(), "POLICY");
                responseEntity = dexClient.text("edu", policy, "1.0", seqNo, param);
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String ebody = responseEntity.getBody();
                    Document doc = DocumentHelper.parseText(ebody);
                    Element ebodyElement = doc.getRootElement();
                    Element data = ebodyElement.element("data");
                    if (data == null) {
                        log.error("请求下载电子保单失败");
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {

                        String fileId = data.getStringValue();
                        t.setEPolicyId(fileId);
                        bindresource(t);
                    }
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }

    }

    /**
     * 学责（学生安全责任保险）
     *
     * @param t
     */
    private void handleXZ(IssuePolicyLogEntity t) {
        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "学责电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20190515003", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "学责电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String ebody = responseEntity.getBody();
                    Document doc = DocumentHelper.parseText(ebody);
                    Element ebodyElement = doc.getRootElement();
                    Element data = ebodyElement.element("data");
                    if (data == null) {
                        log.error("请求下载电子保单失败");
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    }
                    String fileId = data.getStringValue();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }

    }

    private void handleYNXPX(IssuePolicyLogEntity t) {
        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "我学保云南学平险电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20200312004", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "我学保云南学平险电子保单的job,回参：" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String ebody = responseEntity.getBody();
                    Document doc = DocumentHelper.parseText(ebody);
                    Element ebodyElement = doc.getRootElement();
                    Element data = ebodyElement.element("data");
                    if (data == null || "".equals(data)) {
                        log.error("请求下载电子保单失败");
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    }
                    String fileId = data.getStringValue();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }


    }

    private void handleYNFJ(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "云南非九电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20190516016", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "云南非九电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String ebody = responseEntity.getBody();
                    Document doc = DocumentHelper.parseText(ebody);
                    Element ebodyElement = doc.getRootElement();
                    Element data = ebodyElement.element("data");
                    if (data == null) {
                        log.error("请求下载电子保单失败");
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    }
                    String fileId = data.getStringValue();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                    //发送电子保单邮件
                    sendEmail(t.getApplicationFormCode(), "021");
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }


    }


    private void sendEmail(String tbNo, String type) {
        //发送云南非九电子保单邮件
        log.info("--send ynEmail begin--" + tbNo);
        AppDetailProVo detailVos = null;
        ResponseEntity<GenericDataResponse<AppDetailProVo>> appDetailPro;
        AppDetailProParam p = new AppDetailProParam();
        p.setAppCode(tbNo);
        p.setChannelCode("edu");    // 渠道编号
        try {
            appDetailPro = insClient.searchAppDetailPro(p);
            detailVos = appDetailPro.getBody().getData();
            MailDTO mailDTO = new MailDTO();
            HolderForProVO holder = detailVos.getHolder();
            String holderCode = holder.getHolderCode();
            User userholder = userService.findEduUserByCode(holderCode);
            mailDTO.setUserName(userholder.getName());
            mailDTO.setProductName(detailVos.getProductName());
            mailDTO.setEmail(userholder.getEmail());
            mailDTO.setProposalNo(detailVos.getPolicyNo());
            mailDTO.setOrderNo(detailVos.getOrderCode());
            mailDTO.setPolicyNo(Collections.singletonList(tbNo));

            List<PolAttachmentProVO> attachmentList = detailVos.getPolAttachmentList();
            for (PolAttachmentProVO attachment : attachmentList) {
                if ("A002".equals(attachment.getResCode())) {
                    log.info("Search" + tbNo + "policy success");
                    mailDTO.setPolicyId(attachment.getFileUrl());
                }
            }

            if (!StringUtils.isEmpty(userholder.getEmail())) {
                emailsService.sendEmail(mailDTO, type);
            }
        } catch (Exception e) {
            log.error("根据投保单号" + tbNo + "查询投保单信息失败" + e);
        }

        log.info("--send ynEmail end--");
    }

    /**
     * 出单成功 生成消息
     *
     * @param productName
     * @param tbNo
     * @param policyNo
     * @param holderCode
     */
    private void createMessage(String productName, String tbNo, String policyNo, String holderCode) {

        try {

            log.info("出单成功 生成消息 productName:{},tbNo:{},policyNo:{},holderCode:{}", productName, tbNo, policyNo, holderCode);

            MessageInfoEntity entity = new MessageInfoEntity();
            entity.setNoticeState(false);
            entity.setCreateTime(DateUtils.getCurrentTime());
            entity.setMessageTitle("出单成功");
            entity.setMessageContent("您投保的" + productName + "产品（投保单号：" + tbNo + "）已出单成功，保单号为：" + policyNo + ",按照" + productName + "项目（产品）的约定，保险合同成立并生效。");
            entity.setIsDeleted(false);
            entity.setTargetUser(holderCode);
            entity.setMessageType(MESSAGE_TYPE);
            entity.setNoticeType(0);
            entity.setRecordType(1);
            entity.setMessageUrl("/userCenter/insurdetails?data=" + tbNo);
            int num = messageService.addMessageInfo(entity);

            if (num > 0) {
                log.info("生成出单成功消息成功：投保单号{},保单号{},消息内容{}", tbNo, policyNo, entity.getMessageContent());
            } else {
                log.info("生成出单成功消息失败：投保单号{},保单号{}", tbNo, policyNo);
            }
        } catch (Exception e) {
            log.error("生成出单成功消息异常 投保单号{}：，异常信息{}", tbNo, e);
        }
    }

    private void handleSD(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "山东校责电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20190516022", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "山东校责电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String fileId = responseEntity.getBody();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }


    }

    /**
     * 阳光财产安责保护伞
     *
     * @param t
     */
    private void handleAZBHS(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "阳光财产安责保护伞电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                if (t.getIfCode().equals("20200211001")) {
                    responseEntity = dexClient.text("edu", "20200212012", "1.0", seqNo, param);
                } else if (t.getIfCode().equals("20200330006")) {
                    responseEntity = dexClient.text("edu", "20200330012", "1.0", seqNo, param);
                } else if (t.getIfCode().equals("202006171149460")) {
                    responseEntity = dexClient.text("edu", "202006171156520", "1.0", seqNo, param);
                } else if (t.getIfCode().equals("202008191339340")) {
                    responseEntity = dexClient.text("edu", "202008191353580", "1.0", seqNo, param);
                } else {
                    responseEntity = dexClient.text("edu", "20190515016", "1.0", seqNo, param);
                }
                log.info(DateUtils.getCurrentTime() + "阳光财产安责保护伞电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("阳光财产安责保护伞请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    Document doc = DocumentHelper.createDocument();
                    doc = DocumentHelper.parseText(responseEntity.getBody());
                    Element ebodyElement = doc.getRootElement();
                    Element data = ebodyElement.element("data");
                    String fileId = data.getStringValue();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job阳光财产安责保护伞请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

    /**
     * 食品险（校园食品安全责任保险）
     *
     * @param t
     */
    private void handleSPX(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "食品险电子保单的job,入参：" + param);
                //param是第一次返回,需要获取到新地址进行下载
                JSONObject object = (JSONObject) JSONObject.parse(param);
                String url = object.getString("url");
                String newUrl = getNewUrl(t.getApplicationFormCode(), url);
                log.info("实责校责（大地）拼接电子保单 " + newUrl);

                // 拼装下载报文
                Map<String, String> map = new HashMap<>();
                map.put("ApplicationFormCode", t.getApplicationFormCode());
                map.put("url", newUrl);
                String newParam = JsonUtils.toJson(map);
                log.info("实责校责（大地）拼接电子保单新地址为: {} " + newParam);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20190802022", "1.0", seqNo, newParam);
                log.info(DateUtils.getCurrentTime() + "食品险电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("食品险请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    Document doc = DocumentHelper.createDocument();
                    doc = DocumentHelper.parseText(responseEntity.getBody());
                    Element ebodyElement = doc.getRootElement();
                    Element data = ebodyElement.element("data");
                    String fileId = data.getStringValue();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job食品险请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

    /**
     * 徐州学平险（徐州学平意外险/徐州监护人责任险）
     *
     * @param t
     */
    private void handleXZXPX(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {

                Document doc = DocumentHelper.parseText(param);
                Element rootElement = doc.getRootElement();
                String transactionCode = rootElement.element("head").element("transactionCode").getStringValue();

                String company = "";

                if ("108005".equals(transactionCode)) {
                    company = "20190729002";
                } else if ("107003".equals(transactionCode)) {
                    company = "20190729003";
                }

                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "徐州学平险电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", company, "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "徐州学平险电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("徐州学平险请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    Document resultDoc = DocumentHelper.parseText(responseEntity.getBody());
                    Element ebodyElement = resultDoc.getRootElement();
                    Element data = ebodyElement.element("data");
                    String fileId = data.getStringValue();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job徐州学平险请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }


    /**
     * 电子保单统一的格式处理
     *
     * @param t
     */
    private void handleEpolicy(IssuePolicyLogEntity t, IssueEnum issueEnum) {
        //日志id
        String pringLogId = "EDU_" + System.currentTimeMillis();
        String param = t.getParam().replaceAll("&amp;", "&");
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;
        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info("{},{}电子保单的job,入参：{}", pringLogId, issueEnum.getDesc(), param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20190516022", "1.0", seqNo, param);
                log.info("{},{}电子保单的job,回参：{},{}", pringLogId, issueEnum.getDesc(), responseEntity.getBody(), responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200 || StringUtils.isBlank(responseEntity.getBody())) {
                    log.info("{},{}请求下载电子保单失败", pringLogId, issueEnum.getDesc());
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String fileId = responseEntity.getBody();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("{},Job-{}请求下载电子保单失败，投保单号：", pringLogId, t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

    /**
     * 适用于大地保险公司电子保单
     *
     * @param applicationFormCode
     * @param url
     * @return
     */
    private String getNewUrl(String applicationFormCode, String url) {
        url = url.replace("/download", "/download/link");
        try {
            try {
                Thread.sleep(80000);
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setReadTimeout(60000);
                connection.setConnectTimeout(10000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = connection.getInputStream();
                    StringBuffer tStringBuffer = new StringBuffer();

                    BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String sTempOneLine;
                    while ((sTempOneLine = tBufferedReader.readLine()) != null) {
                        tStringBuffer.append(sTempOneLine);
                    }
                    log.info("大地返回新电子保单路径: {}", tStringBuffer.toString());
                    return tStringBuffer.toString();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            log.error(applicationFormCode + ", 保单原地址为：" + url, e);
        }
        return url;
    }

    /**
     * 实责校责（大地）
     *
     * @param t
     */
    private void handleSZXZDD(IssuePolicyLogEntity t) {
        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "实责校责（大地）电子保单的job,入参：" + param);
                //param是第一次返回,需要获取到新地址进行下载
                JSONObject object = (JSONObject) JSONObject.parse(param);
                String url = object.getString("url");
                String newUrl = getNewUrl(t.getApplicationFormCode(), url);
                log.info("实责校责（大地）拼接电子保单 " + newUrl);

                // 拼装下载报文
                Map<String, String> map = new HashMap<>();
                map.put("ApplicationFormCode", t.getApplicationFormCode());
                map.put("url", newUrl);
                String newParam = JsonUtils.toJson(map);
                log.info("实责校责（大地）拼接电子保单新地址为: {} " + newParam);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20190518021", "1.0", seqNo, newParam);
                log.info(DateUtils.getCurrentTime() + "实责校责（大地）电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("实责校责（大地）请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String ebody = responseEntity.getBody();
                    Document doc = DocumentHelper.parseText(ebody);
                    Element ebodyElement = doc.getRootElement();
                    Element data = ebodyElement.element("data");
                    if (data == null) {
                        log.error("实责校责（大地）请求下载电子保单失败");
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {

                        String fileId = data.getStringValue();
                        t.setEPolicyId(fileId);
                        bindresource(t);
                    }
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job实责校责（大地）请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }

    }

    /**
     * 实责校责（太平/中华联合）
     *
     * @param t
     */
    private void handleSZXZ(IssuePolicyLogEntity t) {
        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "实责校责电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                if (t.getIfCode().equals("20190827001")) {
                    responseEntity = dexClient.text("edu", "20191118001", "1.0", seqNo, param);
                } else {
                    responseEntity = dexClient.text("edu", "20190726008", "1.0", seqNo, param.replaceAll("&amp;", "&"));
                }
                log.info(DateUtils.getCurrentTime() + "实责校责电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200 || StringUtils.isBlank(responseEntity.getBody())) {
                    log.error("实责校责请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {


                    String ebody = responseEntity.getBody();
                    if (ebody == null) {
                        log.error("实责校责请求下载电子保单失败");
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {
                        if (t.getIfCode().equals("20190827001")) {
                            Document resultDoc = DocumentHelper.createDocument();
                            resultDoc = DocumentHelper.parseText(ebody);
                            Element ebodyElement = resultDoc.getRootElement();
                            Element data = ebodyElement.element("data");
                            ebody = data.getStringValue();
                        }
                        t.setEPolicyId(ebody);
                        bindresource(t);
                    }
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job实责校责请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }

    }

    /**
     * 食品险（太平）
     *
     * @param t
     */
    private void handleSPXTP(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "食品险（太平）电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                if (t.getIfCode().equals("20190827001") || t.getIfCode().equals("20190909101")) {
                    responseEntity = dexClient.text("edu", "20191118001", "1.0", seqNo, param);

                } else {
                    responseEntity = dexClient.text("edu", "20190802032", "1.0", seqNo, param);

                }
                log.info(DateUtils.getCurrentTime() + "食品险（太平）电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("食品险（太平）请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String fileId = responseEntity.getBody();
                    if (t.getIfCode().equals("20190827001")) {
                        Document resultDoc = DocumentHelper.createDocument();
                        resultDoc = DocumentHelper.parseText(fileId);
                        Element ebodyElement = resultDoc.getRootElement();
                        Element data = ebodyElement.element("data");
                        fileId = data.getStringValue();
                    }
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job食品险（太平）请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

    /**
     * 【实责 校责 阳光】
     *
     * @param t
     */
    private void handleXSZAndXZ(IssuePolicyLogEntity t) {
        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "实责校责电子保单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20190726003", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "实责校责电子保单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("请求下载电子保单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String ebody = responseEntity.getBody();
                    Document doc = DocumentHelper.parseText(ebody);
                    Element ebodyElement = doc.getRootElement();
                    Element data = ebodyElement.element("data");
                    if (data == null) {
                        log.error("请求下载电子保单失败");
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {

                        String fileId = data.getStringValue();
                        t.setEPolicyId(fileId);
                        bindresource(t);
                    }
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job请求下载电子保单失败，投保单号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }

    }

    private void bindresource(IssuePolicyLogEntity t) {
        ResBindQo resBindQo = null;
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;
        // 继续去绑定资源
        resBindQo = new ResBindQo();
        String applicationFormCode = t.getApplicationFormCode();
        resBindQo.setApplicationFormCode(t.getApplicationFormCode());
        ResBindDetailQo resBindDetailQo = new ResBindDetailQo();
        resBindDetailQo.setBizCodeType("01");
        resBindDetailQo.setResCode("A002");
        resBindDetailQo.setResId(ePolicyId);
        resBindDetailQo.setResName("电子保单、保单影印件");
        List<ResBindDetailQo> list = new ArrayList<>();
        list.add(resBindDetailQo);
        resBindQo.setDetailList(list);
        ResponseEntity<GenericListResponse<Map<String, String>>> genericListResponseResponseEntity = null;
        try {
            genericListResponseResponseEntity = insClient.bindResources(resBindQo);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("调用绑定资源接口出错!{}", e);
        }
        String code;
        //出错时，超时时处理
        if (null == genericListResponseResponseEntity) {
            code = "9999";
        } else {
            GenericListResponse<Map<String, String>> body = genericListResponseResponseEntity.getBody();
            code = body.getCode();
            log.info(DateUtils.getCurrentTime() + "调用绑定资源接口返回结果码" + code + ":" + body.getMsg());
        }

        if (!"0000".equals(code)) {
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        } else {
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("2");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

    /**
     * 广东校责、教职工、食品、校车
     *
     * @param t
     * @return
     */
    private void handleGD(IssuePolicyLogEntity t) {
        String findCode = "handleGD_" + System.currentTimeMillis();
        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info("{} 广东校责、食品、教职工、校车电子保单的job,入参：{}", findCode, param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "202008181525000", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "广东校责、食品、教职工、校车电子保单的job,回参：" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("{} 校责、食品、教职工、校车请求下载电子保单失败", findCode);
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String ebody = responseEntity.getBody();
                    if (ebody == null || "".equals(ebody)) {
                        log.error("{} 校责、食品、教职工、校车请求下载电子保单失败", findCode);
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {
                        String fileId = ebody;
                        t.setEPolicyId(fileId);
                        bindresource(t);
                        sendEmailGD(findCode, t.getApplicationFormCode(), "021");
                    }
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("{} job请求下载校责、食品、教职工、校车电子保单失败，投保单号：{}", findCode, t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

    /**
     * 济宁学平（线下批量录单）
     *
     * @param t
     * @return
     */
    private void handleJiNingXPX(IssuePolicyLogEntity t) {
        String findCode = "handleJiNingXPX_" + System.currentTimeMillis();
        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info("{} 新济宁学平电子保单的job,入参：{}", findCode, param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "202008281553420", "1.0", seqNo, param);
                log.info("{} 新济宁学平电子保单的job,回参：{},{}", findCode, responseEntity.getStatusCodeValue(), responseEntity.getBody());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.info("{} 新济宁学平请求下载电子保单失败", findCode);
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    ePolicyId = responseEntity.getBody();
                    if (ePolicyId == null || "".equals(ePolicyId)) {
                        log.info("{} 新济宁学平请求下载电子保单失败 fileId为空", findCode);
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {
                        log.info("{} 新济宁学平请求下载电子保单成功 fileId：{}", findCode, ePolicyId);
                        t.setEPolicyId(ePolicyId);
                        bindresource(t);
                    }
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("{} job请求下载新济宁学平电子保单失败，投保单号：{}, 异常信息:{}", findCode, t.getApplicationFormCode(), e);
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

    /**
     * 济宁学平（线上）
     *
     * @param t
     * @return
     */
    private void handleJiNingXPXOnline(IssuePolicyLogEntity t) {
        String findCode = "handleJiNingXPXOnline_" + System.currentTimeMillis();

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info("{} 新济宁学平（线上）电子保单的job,入参：{}", findCode, param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "202009090117050", "1.0", seqNo, param);
                log.info("{} 新济宁学平（线上）电子保单的job,回参：{},{}", findCode, responseEntity.getStatusCodeValue(), responseEntity.getBody());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.info("{} 新济宁学平（线上）请求下载电子保单失败", findCode);
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    ePolicyId = responseEntity.getBody();
                    if (ePolicyId == null || "".equals(ePolicyId)) {
                        log.info("{} 新济宁学平（线上）请求下载电子保单失败 fileId为空", findCode);
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {
                        log.info("{} 新济宁学平（线上）请求下载电子保单成功 fileId：{}", findCode, ePolicyId);
                        t.setEPolicyId(ePolicyId);
                        bindresource(t);
                    }
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("{} job请求下载新济宁学平（线上）电子保单失败，投保单号：{}, 异常信息：{}", findCode, t.getApplicationFormCode(), e);
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }


    /**
     * 广东4款产品电子保单邮件
     *
     * @param findCode
     * @param tbNo
     * @param type
     */
    private void sendEmailGD(String findCode, String tbNo, String type) {
        log.info("{} 广东4款产品电子保单邮件 投保单号：{}，type：{}", findCode, tbNo, type);
        AppDetailProVo detailVos = null;
        ResponseEntity<GenericDataResponse<AppDetailProVo>> appDetailPro;
        AppDetailProParam p = new AppDetailProParam();
        p.setAppCode(tbNo);
        p.setChannelCode("edu");    // 渠道编号
        try {
            appDetailPro = insClient.searchAppDetailPro(p);
            detailVos = appDetailPro.getBody().getData();
            MailDTO mailDTO = new MailDTO();
            HolderForProVO holder = detailVos.getHolder();
            String holderCode = holder.getHolderCode();
            User userholder = userService.findEduUserByCode(holderCode);
            mailDTO.setUserName(userholder.getName());
            mailDTO.setProductName(detailVos.getProductName());
            mailDTO.setEmail(userholder.getEmail());
            mailDTO.setProposalNo(detailVos.getPolicyNo());
            mailDTO.setOrderNo(detailVos.getOrderCode());
            mailDTO.setPolicyNo(Collections.singletonList(tbNo));

            log.info("{} 广东4款产品电子保单邮件 投保单号：{}，邮件内容：{}", findCode, tbNo, mailDTO);

            List<PolAttachmentProVO> attachmentList = detailVos.getPolAttachmentList();
            for (PolAttachmentProVO attachment : attachmentList) {
                if ("A002".equals(attachment.getResCode())) {
                    log.info("{} 广东4款产品电子保单邮件 投保单号：{}，fileUrl：{}", findCode, tbNo, attachment.getFileUrl());
                    mailDTO.setPolicyId(attachment.getFileUrl());
                }
            }

            if (!StringUtils.isEmpty(userholder.getEmail())) {
                emailsService.sendEmail(mailDTO, type);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("{} 广东4款产品电子保单邮件 根据投保单号 {} 查询投保单信息失败，异常信息：{}", findCode, tbNo, e);
        }

        log.info("{} 广东4款产品电子保单邮件 投保单号：{} 邮件发送完成", findCode, tbNo);

    }

    /**
     * 启东学平险
     *
     * @param t
     * @return
     */
    private void handleQiDong(IssuePolicyLogEntity t) {
        String findCode = "handleQiDong_" + System.currentTimeMillis();

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info("{} 启东学平险电子保单的job,入参：{}", findCode, param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "202009171808110", "1.0", seqNo, param);
                log.info("{} 启东学平险电子保单的job,回参：{},{}", findCode, responseEntity.getStatusCodeValue(), responseEntity.getBody());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.info("{} 启东学平险请求下载电子保单失败", findCode);
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    ePolicyId = responseEntity.getBody();
                    if (ePolicyId == null || "".equals(ePolicyId)) {
                        log.info("{} 启东学平险请求下载电子保单失败 fileId为空", findCode);
                        t.setTimes(times);
                        t.setEPolicyId(ePolicyId);
                        t.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {
                        log.info("{} 启东学平险请求下载电子保单成功 fileId：{}", findCode, ePolicyId);
                        t.setEPolicyId(ePolicyId);
                        bindresource(t);
                    }
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("{} job请求下载启东学平险电子保单失败，投保单号：{}, 异常信息：{}", findCode, t.getApplicationFormCode(), e);
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

}
